<template>
	<view>


		<view>
			<view class="goods_c">
				<view class="type_text">
					已选
				</view>
				<view class="item_r" @click="open">
					<text class="item_text">{{ selectItem.goods_props && selectItem.goods_props.join(' & ') }}</text>
					<text class="iconfont fr icon-xiayiyeqianjinchakangengduo"></text>
				</view>
			</view>
		</view>




		<u-popup :show="show" :round="10" mode="bottom" @close="close">
			<view class="sku_box">
				<view class="goods_msg">
					<view class="g_l">
						<image :src="images[0]" mode=""></image>
					</view>
					<view class="g_price">
						<view class="g_p">
							<text class="sub">￥</text>
							<text>{{ selectItem.retail_price }}</text>
						</view>
						<view class="stock_num">
							库存 {{ selectItem.stock_num }} 件
						</view>
					</view>


					<view class="number-box">
						<view class="n_t">
							购买数量
						</view>
						<u-number-box button-size="28" color="#666" bg-color="#f2f2f2" icon-style="color: #f00"
							@change="valChange"></u-number-box>
					</view>
				</view>


				<view class="sku_list" v-for="(item, i) in specList">
					<view class="item">
						<view class="item_name">
							{{ item.spec_name }} ({{ item.valueList.length }})
						</view>
						<view class="item_key">
							<view v-for="(items, j) in item.valueList">
								<text :class="items.check && `active`"
									@click="selectItems(i, j)">{{ items.spec_value }}</text>
							</view>
						</view>
					</view>

				</view>

				<view class="btn_box">
					<view class="all_check">
						批量下单请在微信聊天记录里选择文件
					</view>
					<button class="btn add_cart" @click="handleAddCart">批量下单</button>
					<button class="btn buy_now" @click="handleBuyNow">立即购买</button>
				</view>

			</view>
		</u-popup>


		<u-popup :show="dShow" :round="10" mode="bottom" @close="dClose" :closeable="true">
			<view class="pop">
				<view class="titles">批量导入地址</view>

				<view class="d_box">
					<view class="nun_box">
						地址导入成功：<text>{{ upMsg.num }}</text> 条
					</view>

					<view class="nun_box">
						地址导入失败：<text>{{ upMsg.false_num }}</text> 条
					</view>
					<view class="nun_box" v-if="upMsg.false_num">
						失败原因：
					</view>



					<view class="d_list" v-if="upMsg.false_num">
						<view class="item" v-for="(val, key) in upMsg.errorArr">
							<text class="mark"></text>
							<text class="content">{{ val }}</text>
						</view>
					</view>

					<button class="btn add_cart" @click="dClose">确认</button>
				</view>

			</view>
		</u-popup>
	</view>
</template>

<script setup>
	import {
		ref,
		defineProps,
		defineEmits,
		watch,
		computed
	} from 'vue';
	import {
		onShow
	} from '@dcloudio/uni-app';
	import {
		useAuthStore
	} from '@/stores/user.js';
	import {
		COMMON
	} from "@/utils/commom.js"
	import {
		add_cart
	} from "@/api/goods.js"
	import {
		BASE_URL
	} from "@/utils/request.js"

	// 定义 props
	const props = defineProps({
		sku: {
			type: Object,
			required: true, // 根据需要设置为 required
		},
		images: {
			type: Array,
			required: true, // 根据需要设置为 required
		},
		sku_show: {
			type: Boolean,
			required: true, // 根据需要设置为 required
		}
	});



	const emit = defineEmits(['async_price', 'asyncSku']);


	const authStore = useAuthStore();

	// 定义响应式状态
	const show = ref(false);
	const num = ref(1);
	const skuList = ref([]);
	const specList = ref([]);
	const selectItem = ref({});
	const upMsg = ref([]);
	const dShow = ref(false);


	onShow(() => {
		authStore.initialize();
	})

	// 监听变化
	watch(() => props.sku, (value, old) => {
		skuList.value = value.skuList;
		specList.value = value.specList;
		//console.log(JSON.stringify(specList.value))
		firstItem(skuList.value, specList.value);
	}, {
		deep: true
	});

	watch(() => props.sku_show, (newValue, oldValue) => {
		show.value = newValue
	});


	// 设置规格默认第一项选中
	function firstItem(skuList, specList) {
		const concatenatedIds = [];

		specList.forEach(spec => {
			if (Array.isArray(spec.valueList) && spec.valueList.length > 0) {

				spec.valueList.forEach((item, index) => {
					item.check = index === 0;
				});

				// 当前选中的规格spec_value_id
				concatenatedIds.push(spec.valueList[0].spec_value_id);
			}
		});

		let goods_sku_id = concatenatedIds.join('_');

		// 选中的规格商品
		selectedSku(skuList, goods_sku_id);
	}

	// 选择规格
	function selectItems(i, j) {
		// 创建一个新的 specList 副本以确保响应式更新
		const updatedSpecList = specList.value.map((specItem, index) => {
			if (index === i) {
				// 当前规格：将所有 value 的 check 设置为 false，除了指定的 j
				return {
					...specItem,
					valueList: specItem.valueList.map((valueItem, subIndex) =>
						subIndex === j ? {
							...valueItem,
							check: true
						} : {
							...valueItem,
							check: false
						}
					),
				};
			} else {
				// 其他规格保持不变
				return specItem;
			}
		});


		// 替换整个 specList 以触发响应式更新
		specList.value = updatedSpecList;

		let goods_sku_id = [];
		// 更新选中的项
		let checkedItems = updatedSpecList
			.flatMap((spec) =>
				spec.valueList
				.filter((item) => item.check)
				.map((item) => ({
					spec_value_id: item.spec_value_id
				}))
			);

		// 更新选中的 goods_sku_id
		goods_sku_id = checkedItems.map((item) => item.spec_value_id);
		goods_sku_id = goods_sku_id.join('_');

		// 选中的规格商品
		selectedSku(skuList.value, goods_sku_id);
	}

	// 选中的规格商品
	function selectedSku(skuList, goods_sku_id) {
		for (let i = 0; i < skuList.length; i++) {
			if (skuList[i].goods_sku_id === goods_sku_id) {
				// 当前选择的规格商品
				selectItem.value = skuList[i];
			}
		}

		// 回调商品详情选中的规格商品
		emit('async_price', selectItem.value);
	}

	// 加入购物车
	function handleAddCart() {
		console.log(selectItem.value.goods_sku_id)
		wx.chooseMessageFile({
			count: 1,
			type: 'file',
			success(res) {
				uni.showLoading({
					title: '上传中'
				});
				const tempFilePaths = res.tempFiles
				let filename = res.tempFiles[0].name
				if (filename.lastIndexOf('.xlsx') == filename.length - 5 || filename.lastIndexOf('.xls') ==
					filename.length - 4) {
					uni.uploadFile({
						url: BASE_URL + `api.php?m=Api&c=Order&a=import_retail`,
						filePath: tempFilePaths[0].path,
						name: 'file',
						formData: {
							token: uni.getStorageSync('user_info').token || 0,
							goods_sku_id: selectItem.value.id
						},
						success: (uploadFileRes) => {
							uploads(JSON.parse(uploadFileRes.data))
							uni.hideLoading();
						}
					});
				} else {
					//客制化提示文件类型错误
					uni.showToast({
						title: '请选择xlsx或者xls文件',
						icon: 'error',
						duration: 2000
					});
				}

			}
		})
	}
	
	function dClose() {
		if(upMsg.value.num){
			uni.reLaunch({
				url: '/pages/order/index?type=0'
			})
		}
		dShow.value = false;
	}

	function uploads(data) {
		if (data.status) {
			upMsg.value = data.data;
			dShow.value = true
		} else {
			COMMON.Toast(`data.msg`)
		}
	}

	//  立即购买
	function handleBuyNow() {
		if (!authStore.isLogin) {
			COMMON.toLogin();
			return
		}

		if (selectItem.value.stock_num < num.value || selectItem.value.stock_num == 0) {
			COMMON.Toast("库存不足");
		} else {
			uni.navigateTo({
				url: `/pages/procure/checkout?goods_id=${selectItem.value.goods_id}&goods_num=${num.value}&goods_sku_id=${selectItem.value.id}&goods_price=${selectItem.value.goods_price}`
			});
		}

	}



	// 打开弹窗的方法
	const open = () => {
		show.value = true;
	};

	// 关闭弹窗的方法
	const close = () => {
		show.value = false;
		emit('asyncSku', false);

	};

	// 获取当前选择数量
	function valChange(e) {
		num.value = e.value;
	}
</script>

<style lang="scss" scoped>
	@import '@/static/css/goods_components.scss';

	.sku_box {
		padding: 50rpx;
		min-height: 50vh;
		overflow: hidden;
		position: relative;

		.goods_msg {
			width: 100%;
			overflow: hidden;

			.g_l {
				width: 100rpx;
				height: 100rpx;
				border-radius: 5px;
				overflow: hidden;
				float: left;
				border: 1px solid #f8f8f8;

				image {
					width: 100%;
					height: 100%;
				}
			}

			.g_price {
				float: left;
				padding-left: 30rpx;

				.sub {
					font-size: 22rpx;
					font-weight: 400;
				}

				text {
					font-size: 38rpx;
					color: #f00;
					font-weight: 600;
				}


				.stock_num {
					font-size: 24rpx;
					color: #777;
					padding-top: 15rpx;
				}
			}


			.number-box {
				float: right;
				margin: 0 20rpx;

				.n_t {
					font-size: 24rpx;
					margin-bottom: 20rpx;
					color: #666;
				}
			}
		}

		.sku_list {
			width: 100%;
			overflow: hidden;
			margin-top: 50rpx;

			.item {
				width: 100%;
				overflow: hidden;

				.item_name {
					font-size: 28rpx;
					padding: 30rpx 0;
					font-weight: 600;
				}

				.item_key {
					display: flex;
					flex-wrap: wrap;

					text {
						display: flex;
						align-items: center;
						justify-content: center;
						background: #eee;
						margin-right: 20rpx;
						margin-bottom: 20rpx;
						border-radius: 100rpx;
						min-width: 60rpx;
						padding: 10rpx 20rpx;
						font-size: 26rpx;
						color: #666;
					}

					.active {
						background: linear-gradient(to right, #f9211c, #ff6335);
						color: #fff;
					}
				}
			}
		}

		.btn_box {
			width: 85%;
			overflow: hidden;
			position: absolute;
			left: 0;
			right: 0;
			bottom: 0;
			margin: 30rpx auto 0;
			z-index: 100;

			.btn {
				height: 70rpx;
				line-height: 70rpx;
				border-radius: 100rpx;
				font-size: 28rpx;
				color: #fff;
				width: 50%;
				float: left;
			}

			.add_cart {
				border-radius: 100px 0 0 100px;
				background: linear-gradient(to right, #ffa600, #ffbb00);
			}

			.buy_now {
				border-radius: 0 100px 100px 0;
				background: linear-gradient(to right, #f9211c, #ff6335);
			}


		}
	}

	.all_check {
		width: 100%;
		overflow: hidden;
		padding: 20rpx 0;
		text-align: center;
		font-size: 26rpx;
		color: #f00;
	}



	.pop {
		overflow: hidden;
		position: relative;
		z-index: 99;

		.titles {
			overflow: hidden;
			padding: 20rpx;
			font-size: 28rpx;
			text-align: center;
			color: #333;
			border-bottom: 1px solid #eee;
		}

		.d_box {
			padding: 55rpx;
			max-height: 65vh;
			overflow: hidden;

			.nun_box {
				padding: 10rpx 0;
				font-size: 28rpx;

				text {
					font-size: 40rpx;
					color: #f00;
					font-weight: bold;
					padding: 0 20rpx;
				}
			}

			.d_list {
				height: 35vh;
				padding: 20rpx 0;
				overflow: hidden;
				overflow-y: auto;
				margin-bottom: 20rpx;

				.item {
					width: 100%;
					display: inline-block;
					height: 60rpx;

					.mark {
						width: 30rpx;
						height: 30rpx;
						float: left;
						border-radius: 100%;
						background-color: #666;
						position: relative;

						&::before {
							content: "";
							display: block;
							position: absolute;
							height: 40rpx;
							border: 1px solid #000;
							left: 13rpx;
							top: 30rpx;
							z-index: 10
						}
					}

					.content {
						float: left;
						position: relative;
						top: -10rpx;
						padding-left: 20rpx;
					}

				}
			}

			.btn {
				margin-top: 30rpx;
				height: 80rpx;
				line-height: 80rpx;
				border-radius: 100rpx;
				font-size: 28rpx;
				color: #fff;
			}

			.add_cart {
				background: linear-gradient(to right, #ffa600, #ffbb00);
			}
		}
	}
</style>